import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core'
import { observable } from 'mobx-angular'
import { MatSelectionList } from '@angular/material'
import { autorun } from 'mobx'
import * as R from 'ramda'

const ITEMS = [
  { id: 1, name: 1 },
  { id: 2, name: 2 },
  { id: 3, name: 3 },
  { id: 4, name: 4 },
  { id: 5, name: 5 },
]

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: [ './list.component.css' ]
})
export class ListComponent implements OnInit, AfterViewInit {
  @observable
  items = ITEMS
  @observable
  selected = []

  @ViewChild(MatSelectionList) listUI

  constructor() {
    autorun(() => {
      console.log(JSON.stringify(this.selected))
    })
  }

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.listUI.selectedOptions.onChange.subscribe(({ source }) => {
      if (source) {
        const prev = this.selected.slice()
        const next = R.pipe(R.map(opt => opt.value.id), R.uniq)(source.selected)
        const diff = R.symmetricDifference(prev, next)

        console.log('change', prev, next, diff)
        if (diff.length > 0) {
          console.log('need change')
          this.selected = next
        }
      }
    })
  }

  onClick() {
    this.items = ITEMS
  }

  onSelect0() {
  }
}
